﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using System.IO;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Shell;
using DBCSCodePage;

namespace NGA
{
    public partial class MainPage : PhoneApplicationPage
    {
        private UserInfo userinfo;

        private const string _settingLabelAppUser = "username";
        private const string _settingLabelAppPassword = "password";
        private const string _settingLabelAppLoginType = "logintype";

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // read saved log info
            userinfo = new UserInfo();
            // use saved username
            var settings = IsolatedStorageSettings.ApplicationSettings;
            if (settings.Contains(_settingLabelAppUser)) //exist?
            {
                userinfo.UserName = settings[_settingLabelAppUser].ToString();
            }
            else
            {
                settings.Add(_settingLabelAppUser, string.Empty);
            }
            if (settings.Contains(_settingLabelAppPassword)) //exist?
            {
                userinfo.Password = settings[_settingLabelAppPassword].ToString();
            }
            else
            {
                settings.Add(_settingLabelAppPassword, string.Empty);
            }
            if (settings.Contains(_settingLabelAppLoginType)) //exist?
            {
                LoginType.SelectedItem = settings[_settingLabelAppLoginType].ToString();
            }
            else
            {
                settings.Add(_settingLabelAppLoginType, string.Empty);
            }
            _app_username.DataContext = userinfo;
            _app_password.DataContext = userinfo;

            loginProgress.Visibility = System.Windows.Visibility.Collapsed;

            // auto log in
#if DEBUG
            //UserLoginProcess();
#endif
        }

        private void ApplicationBarIconButton_Login_Click(object sender, EventArgs e)
        {
            UserLoginProcess();
        }

        private void UserLoginProcess()
        {
            bool isOK;
            string userName = string.Empty;
            string password = string.Empty;
            string cookie = string.Empty;

            var settings = IsolatedStorageSettings.ApplicationSettings;
            if (settings.Contains(_settingLabelAppUser)) //exist?
            {
                if (_app_username.Text.ToString() != string.Empty)
                {
                    settings[_settingLabelAppUser] = _app_username.Text.ToString();
                }
            }
            else
            {
                settings.Add(_settingLabelAppUser, _app_username.Text.ToString());
            }
            if (settings.Contains(_settingLabelAppPassword)) //exist?
            {
                if (_app_password.Password.ToString() != string.Empty)
                {
                    settings[_settingLabelAppPassword] = _app_password.Password.ToString();
                }
            }
            else
            {
                settings.Add(_settingLabelAppPassword, _app_password.Password.ToString());
            }
            if (settings.Contains(_settingLabelAppLoginType)) //exist?
            {
                settings[_settingLabelAppLoginType] = LoginType.SelectedItem.ToString();
            }
            else
            {
                settings.Add(_settingLabelAppPassword, LoginType.SelectedItem.ToString());
            }

            // for remove
//          settings.Remove(appUser); //remove
            
            var loginCount = "loginCount";
            var count = 0;
            if (settings.Contains(loginCount)) //exist?
            {
                isOK = settings.TryGetValue<int>(loginCount, out count);
                if (isOK)
                {
                    count++;
                    settings[loginCount] = count; //update
                }
            }
            else
            {
                settings.Add(loginCount, count);
            }

            settings.Save(); //save

            isOK = settings.TryGetValue<int>(loginCount, out count); //get value
            if (isOK)
            {
//                MessageBox.Show("Login count:" + count.ToString());
            }

            // UI
            _app_username.IsEnabled = false;
            _app_password.IsEnabled = false;
            LoginType.IsEnabled = false;
            loginProgress.Visibility = System.Windows.Visibility.Visible;

            /*
            HttpHandler login = new HttpHandler(
                "http://account.178.com/q_account.php?_act=login",
                "type=username&email=duying0425@163.com&password=sjdkfl",
                System.Text.Encoding.UTF8,
                LogResultAssert);
            */
            /*
            HttpHandler login = new HttpHandler("http://bbs.ngacn.cc/nuke.php?func=login",
                "login_type=use_id&username=702938&password=sjdkfl&expires=2592000",
                DBCSEncoding.GetDBCSEncoding("gb2312"),
                LogResultAssert);
            */
            string _logintype = null;
            switch (LoginType.SelectedIndex)
            {
                case 0:
                    _logintype = "use_name";
                    break;
                case 1:
                    _logintype = "use_id";
                    break;
                case 2:
                    _logintype = "use_mail";
                    break;
                default:
                    _logintype = "use_name";
                    break;
            }
            HttpHandler login = new HttpHandler(
                App.HTTP_DOMAIN + "nuke.php?func=login",
                "login_type=" + _logintype + "&username=" + _app_username.Text + "&password=" + _app_password.Password.ToString() + "&expires=2592000",
                DBCSEncoding.GetDBCSEncoding("gb2312"),
                LogResultAssert);
            
        }

        private bool LogResultAssert(String result)
        {
            //default failure
            bool ret = false;
            try
            {
                if (result.IndexOf("登录成功") != -1)
                {
                    // success
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        //MessageBox.Show("Login SUCCEED");
                        NavigationService.Navigate(new Uri("/ContentPage.xaml?update=&fid=-7", UriKind.Relative));
                    });
                    ret = true;
                }
                else if (result.IndexOf("登录失败") != -1)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("Login FAILURE");
                    });
                }
                else
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("Login ERROR");
                    });
                }
            }
            catch (SystemException e)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("Error:" + e.ToString());
                });
            }

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                _app_username.IsEnabled = true;
                _app_password.IsEnabled = true;
                LoginType.IsEnabled = true;
                loginProgress.Visibility = System.Windows.Visibility.Collapsed;
            });

            return ret;
        }

        private void ApplicationBarIconButton_Reset_Click(object sender, EventArgs e)
        {
            _app_username.Text = string.Empty;
            _app_password.Password = string.Empty;
        }
    }
}